<template>
    <div class="page">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-lx-tag"></i> 学生成绩管理</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <div class="container">
            <div class="operating" v-if="viewCommit">
                <span>成绩比例设置</span>
                <el-select class="select" @change="changePercent" v-model="gradePercent" placeholder="评分比例" size="small" :disabled="hasCommit">
                    <el-option v-for="percent in gradePercentArr" :key="percent" :value="percent"></el-option>
                </el-select>

                <el-button type="success" @click="saveGrades" :disabled="hasCommit">保存</el-button>
                <el-button type="primary" @click="commitGrades" :disabled="hasCommit">提交</el-button>
            </div>
            <el-table :data="students" border class="table" ref="multipleTable" header-cell-class-name="table-header">
                <el-table-column prop="student_id" label="学号" width="180" align="center"></el-table-column>
                <el-table-column prop="student_name" label="姓名"></el-table-column>
                <el-table-column prop="student_major" label="专业"></el-table-column>
                <el-table-column prop="regular_grade" label="平时成绩">
                    <template slot-scope="scope">
                        <el-popover placement="top" width="160" v-model="regularPopoverVisible[scope.$index]">
                            <div style="text-align: right; margin: 0">
                                <el-input :disabled="hasCommit" type="number" v-model.number="tempGrade" placeholder="请输入平时成绩"></el-input>
                                <el-button :disabled="hasCommit" type="primary" size="mini" @click="confirmChangeRegularGrade(scope.$index, tempGrade)"
                                    >确定</el-button
                                >
                            </div>

                            <el-tag
                                class="grade"
                                :type="scope.row.regular_grade < 60 ? 'danger' : scope.row.regular_grade < 80 ? 'info' : 'success'"
                                slot="reference"
                                @click="clickCellGrade(scope.row.regular_grade)"
                            >
                                {{ scope.row.regular_grade ? scope.row.regular_grade : '暂无成绩' }}
                            </el-tag>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="final_exam_grade" label="期末成绩">
                    <template slot-scope="scope">
                        <el-popover placement="top" width="160" v-model="finalPopoverVisible[scope.$index]">
                            <div style="text-align: right; margin: 0">
                                <el-input :disabled="hasCommit" type="number" v-model.number="tempGrade" placeholder="请输入期末成绩"></el-input>
                                <el-button :disabled="hasCommit" type="primary" size="mini" @click="confirmChangeFinalGrade(scope.$index, tempGrade)"
                                    >确定</el-button
                                >
                            </div>

                            <el-tag
                                class="grade"
                                :type="scope.row.final_exam_grade < 60 ? 'danger' : scope.row.final_exam_grade < 80 ? 'info' : 'success'"
                                slot="reference"
                                @click="clickCellGrade(scope.row.final_exam_grade)"
                            >
                                {{ scope.row.final_exam_grade ? scope.row.final_exam_grade : '暂无成绩' }}
                            </el-tag>
                        </el-popover>
                    </template>
                </el-table-column>
                <el-table-column prop="grade_flag" label="成绩标志"></el-table-column>
                <el-table-column prop="total_grade" label="总评成绩">
                    <template slot-scope="scope">
                        <el-tag :type="scope.row.total_grade < 60 ? 'danger' : ''">
                            {{ scope.row.total_grade ? scope.row.total_grade : '暂无成绩' }}
                        </el-tag>
                    </template>
                </el-table-column>
                <!-- <el-table-column prop="test_nature" label="考试性质"></el-table-column> -->
                <el-table-column prop="remark" label="备注"></el-table-column>
                
            </el-table>
        </div>
    </div>
</template>

<script>
import { postRequest, getRequest } from '../../api';
export default {
    name: 'GradeManage',
    components: {},
    data() {
        return {
            courseId: '',
            currentPage: 1,
            itemOfPage: 10,
            totalPages: 0,
            students: [],
            gradePercent: '',
            gradePercentObj: {},
            gradePercentArr: global.GRADE_PERCENT_ARRAY,
            tempGrade: '',
            hasCommit: false,
            viewCommit: true,
            // 控制每个 popover是否可见
            regularPopoverVisible: [],
            finalPopoverVisible: []
        };
    },
    created() {
        if (this.$route.query.courseId) {
            this.courseId = this.$route.query.courseId;
            this.getStudentGrades();
            this.getGradePercent();
        } else {
            this.$message.error('您还未指定课程, 请前往成绩录入页面!');
        }
        if (this.$route.query.is_commit) {
            console.log(this.$route.query.is_commit);
            this.hasCommit = this.$route.query.is_commit;
            // 只为观察
            this.viewCommit = false;
        }
    },
    methods: {
        getStudentGrades() {
            getRequest(
                '/login/teacher/grade/get_studnet_grade',
                { course_id: this.courseId, current_page: this.currentPage, itemsofpage: this.itemOfPage },
                global.CONTENT_TYPE_URLENCODED
            ).then(
                res => {
                    if (res.code == 200) {
                        this.regularPopoverVisible = [];
                        this.finalPopoverVisible = [];
                        this.students = res.data.content;
                        this.totalPages = res.data.total_pages;
                        for (let i = 0; i < res.data.content.length; i++) {
                            this.regularPopoverVisible.push(false);
                            this.finalPopoverVisible.push(false);
                        }
                    }
                },
                err => {}
            );
        },
        getGradePercent() {
            getRequest('/login/teacher/grade/get_grade_percent', { course_id: this.courseId }, global.CONTENT_TYPE_URLENCODED).then(
                res => {
                    if (res.code == 200) {
                        this.gradePercent = res.data;
                        this.parsingPercent(this.gradePercent);
                    } else {
                        this.$message.error('获取成绩百分比失败！');
                    }
                },
                err => {}
            );
        },
        changePercent(value) {
            postRequest(
                '/login/teacher/grade/set_grade_percent',
                { course_id: this.courseId, percent: value },
                global.CONTENT_TYPE_URLENCODED
            ).then(
                res => {
                    if (res.code == 200) {
                        this.$message.success('修改课程成绩百分比成功！');
                        this.parsingPercent(value);

                        // 重新计算
                        let students = this.students;
                        for (let i = 0;i < students.length;i++) {
                            if (students[i].regular_grade && students[i].final_exam_grade) {
                                this.students[i].total_grade = this.computeGrade(students[i].regular_grade, students[i].final_exam_grade);
                            }
                        }
                    } else {
                        this.$message.error('修改课程成绩百分比失败！');
                    }
                },
                err => {}
            );
        },
        // 解析百分比
        parsingPercent(value) {
            let tempArr = value.split(':');
            // 平时
            this.gradePercentObj['regular'] = Number(tempArr[0]);
            // 期末
            this.gradePercentObj['final'] = Number(tempArr[1]);
        },
        confirmChangeRegularGrade(index, grade) {
            if (grade > 100 || grade < 0) {
                this.$message.error('您输入的平时成绩必须在 0~100以内');
                return;
            }
            this.students[index].regular_grade = grade;
            // 复原
            this.tempGrade = 0;
            // 计算

            this.students[index].total_grade = this.computeGrade(grade, this.students[index].final_exam_grade);
            this.regularPopoverVisible[index] = false;
        },
        // 确认更改
        confirmChangeFinalGrade(index, grade) {
            if (grade > 100 || grade < 0) {
                this.$message.error('您输入的期末成绩必须在 0~100以内');
                return;
            }
            this.students[index].final_exam_grade = grade;
            this.tempGrade = 0;
            this.students[index].total_grade = this.computeGrade(this.students[index].regular_grade, grade);
            this.finalPopoverVisible[index] = false;
        },
        // 点击成绩后的回调函数
        clickCellGrade(grade) {
            if (grade) {
                this.tempGrade = Number(grade);
            } else {
                this.tempGrade = '';
            }
        },
        // 计算总成绩
        computeGrade(regular, final) {
            let percentObj = this.gradePercentObj;
            if (regular && final) {
                let grade = regular * percentObj['regular'] + final * percentObj['final'];
                return (grade * 0.1).toFixed(1);
            } else {
                return null;
            }
        },
        // 保存成绩
        saveGrades() {
            let grades = [];
            for (let i = 0;i < this.students.length;i++) {
                let temp = this.students[i];
                temp['course_id'] = this.courseId;
                grades.push(temp);
            }
            postRequest('/login/teacher/grade/entry_grade', grades).then(res => {
                console.log(res);
                if (res.code == 200) {
                    this.$message.success('保存成绩成功!');
                } else if (res.code == 402) {
                    this.$message.error(res.msg);
                }
            }, err => {
                this.$message.error('保存成绩失败！');
            })
        },
        commitGrades() {
            let grades = [];
            for (let i = 0;i < this.students.length;i++) {
                let temp = this.students[i];
                temp['course_id'] = this.courseId;
                grades.push(temp);
            }
            postRequest('/login/teacher/grade/commit_grade', grades).then(res => {
                console.log(res);
                if (res.code == 200) {
                    this.$message.success('提交成功!');
                    this.hasCommit = true;
                } else if (res.code == 402) {
                    this.$message.error(res.msg);
                }
            }, err => {
                this.$message.error('提交失败！');
            })
        }
    },
    watch: {
    }
};
</script>

<style scoped>
.operating {
    float: right;
    height: 45px;
}
.select {
    margin: 5px;
}
.grade {
    cursor: pointer;
}
</style>
